use derive_builder::Builder;
use serde::{Deserialize, Serialize};

use crate::error::Error;
use crate::mapper::ValueMapper;
use crate::modeling::{Class, ClassAttributeBuilder, ClassBuilder, ClassGetter, ValueType};
use crate::modeling::{
    ClassAttributePersistence, ClassPersistence, ClassPersistenceBuilder, ClassPersistenceGetter,
    ClassRelation, ClassRelationGetter, Value,
};

const INSTALLED_APPLICATION_CLASS_IDENTIFIER: &'static str = "g01_installed_application";

const INSTALLED_APPLICATION_CLASS_NAME: &'static str = "installed_application";

const INSTALLED_APPLICATION_TABLE_NAME: &'static str = "_g01_installed_applications";

#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub enum InstalledApplicationType {
    /// Agent
    #[default]
    #[serde(rename = "agent")]
    Agent,
    /// G01Server
    #[serde(rename = "g01server")]
    G01Server,
    /// ChatFlow
    #[serde(rename = "chatflow")]
    ChatFlow,
    /// custom h5
    #[serde(rename = "custom_h5")]
    CustomH5,
}

#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
#[builder(name = "InstalledApplicationBuilder")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "Error"))]
pub struct InstalledApplication {
    /// id
    pub id: i64,
    /// identifier
    pub identifier: String,
    /// 名称
    pub name: String,
    /// 名称
    pub title: String,
    /// 图标
    pub icon: Option<String>,
    /// 类型
    pub application_type: InstalledApplicationType,
    /// 文件路径
    pub version: Option<String>,
    /// 文件路径
    pub installed_path: String,
    /// 数据源路径
    pub datasource: Option<String>,
    /// 安装时间
    pub installed_at: i64,
    /// 选项
    pub options: Option<String>,
    /// 备注
    pub description: String,
    /// 创建时间
    pub created_at: i64,
    /// 更新时间
    pub updated_at: i64,
}

//
crate::impl_from_value!(InstalledApplication);
crate::impl_class_persistence_getter!(InstalledApplication, INSTALLED_APPLICATION_TABLE_NAME);
crate::impl_class_relations_getter!(InstalledApplication, vec![]);

impl ClassGetter for InstalledApplication {
    fn get_name() -> anyhow::Result<String> {
        Ok(String::from(INSTALLED_APPLICATION_CLASS_NAME))
    }
    fn get_identifier() -> anyhow::Result<String> {
        Ok(String::from(INSTALLED_APPLICATION_CLASS_IDENTIFIER))
    }
    fn get_class() -> anyhow::Result<Class> {
        let mut attribute_builder = ClassAttributeBuilder::default();
        attribute_builder.class_identifier(INSTALLED_APPLICATION_CLASS_IDENTIFIER);

        let mut commons = crate::modeling::common_attributes_with_builder(&attribute_builder)?;
        let mut append = vec![
            attribute_builder
                .clone()
                .name("application_type")
                .title("类型")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("version")
                .title("版本")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("installed_path")
                .title("安装路径")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("datasource")
                .title("数据源")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("installed_at")
                .title("安装时间")
                .data_type(ValueType::Timestamp)
                .build()?,
        ];
        append.append(&mut commons);
        append.sort_by(|a, b| a.position.cmp(&b.position));

        let clazz = ClassBuilder::default()
            .identifier(INSTALLED_APPLICATION_CLASS_IDENTIFIER)
            .name(INSTALLED_APPLICATION_CLASS_NAME)
            .data_is_type(false)
            .is_persistent(true)
            .primary_key(String::from("identifier"))
            .attributes(append)
            .build()?;
        Ok(clazz)
    }
}
